import { Injectable, Logger } from '@nestjs/common';
import { Cron } from '@nestjs/schedule';
import { FeishuService } from '../feishu/feishu.service';
import { WechatService } from '../wechat/wechat.service';
import dayjs from 'dayjs';

@Injectable()
export class TasksService {
  private readonly logger = new Logger(TasksService.name);

  constructor(
    private readonly feishuService: FeishuService,
    private readonly wechatService: WechatService,
  ) {}

  /**
   * 获取飞书表格中的数据，找到第一条 publish 为 0 的数据，然后发送微信消息
   */

  // 每天17:50执行，更新缓存数据
  @Cron('0 50 17 * * *')
  async updateCacheDataCron(): Promise<void> {
    const currentDate = dayjs().format('YYYY-MM-DD');
    this.logger.log(`开始执行每日缓存更新任务 [${currentDate}]`);

    try {
      const result = await this.feishuService.updateCachedData();
      if (result) {
        this.logger.log('缓存数据更新成功');
      } else {
        this.logger.error('缓存数据更新失败');
      }
    } catch (error) {
      const errorObj =
        error instanceof Error ? error : new Error(String(error));
      this.logger.error('执行缓存更新任务出错', errorObj);
    }
  }

  @Cron('0 0 18-23 * * *') // 每天晚上6点到23点，每小时执行一次
  async handleFeishuDataCron(isPublish = false): Promise<void> {
    const startMessage = '开始执行定时任务：获取飞书表格数据并发送微信消息';
    this.logger.log(startMessage);

    try {
      // 获取飞书表格数据
      const result = await this.feishuService.getTableRecords();

      if (!result.success || !result.data) {
        const errorMessage = `获取飞书表格数据失败: ${result.message}`;
        this.logger.error(errorMessage);
        return;
      }

      // 打印获取到的数据条数
      this.logger.log(
        `成功获取飞书表格数据，共 ${result.data.items.length} 条记录`,
      );

      // 打印每条记录的 publish 字段值
      result.data.items.forEach((item, index) => {
        const publishValue = item.fields.publish;
        const publishType = typeof publishValue;
        this.logger.log(
          // eslint-disable-next-line @typescript-eslint/restrict-template-expressions
          `记录 ${index + 1}，ID: ${item.record_id}，publish 值: ${publishValue}，类型: ${publishType}`,
        );
      });

      // 查找第一条 publish 为 0 的数据
      const targetRecord = result.data.items.find((item) => {
        if (isPublish) {
          return item.fields.publish === 1 || item.fields.publish === '1';
        } else {
          return item.fields.publish === 0 || item.fields.publish === '0';
        }
      });

      if (!targetRecord) {
        this.logger.log(
          `未找到 publish 为 ${isPublish ? '1' : '0'} 的数据，本次任务结束`,
        );
        return;
      }

      this.logger.log(
        `找到 publish 为 0 的数据，ID: ${targetRecord.record_id}`,
      );

      // 获取需要发送的内容
      let content = '无内容';
      if (targetRecord.fields.post_title) {
        content =
          typeof targetRecord.fields.post_title === 'object'
            ? JSON.stringify(targetRecord.fields.post_title)
            : // eslint-disable-next-line @typescript-eslint/no-base-to-string
              String(targetRecord.fields.post_title);
      }

      // 添加链接到内容中
      if (targetRecord.fields.link) {
        const link =
          typeof targetRecord.fields.link === 'object'
            ? JSON.stringify(targetRecord.fields.link)
            : // eslint-disable-next-line @typescript-eslint/no-base-to-string
              String(targetRecord.fields.link);
        content += '\n\n链接: ' + link;
      }

      const groupName = '老中医'; // 默认群组名称

      // 发送微信消息
      const sendResult = await this.wechatService.sendMessage({
        groupName,
        content,
      });

      if (sendResult.success) {
        const successMessage = `成功发送微信消息到群组: ${groupName}`;
        this.logger.log(successMessage);

        // 发送成功后，更新飞书表格中的 publish 字段为 1
        try {
          const updateResult = await this.feishuService.updateTableRecord(
            targetRecord.record_id,
            { publish: 1 },
          );

          if (updateResult.success) {
            this.logger.log(
              `成功更新飞书表格记录，ID: ${targetRecord.record_id}, publish 已设置为 1`,
            );
          } else {
            this.logger.error(`更新飞书表格记录失败: ${updateResult.message}`);
          }
        } catch (updateError) {
          this.logger.error('更新飞书表格记录出错', updateError);
        }
      } else {
        const errorMessage = `发送微信消息失败: ${sendResult.message}`;
        this.logger.error(errorMessage);
      }
    } catch (error) {
      const errorObj =
        error instanceof Error ? error : new Error(String(error));
      this.logger.error('执行定时任务出错', errorObj);
    }
  }
}
